package com.mchat.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class JwtAuthenticationFilter implements WebFilter {


    private final List<String> excludedPath= List.of("/user/search","/user/login","/user/register","/send-code","/user/reset-password");

    @Resource
    JwtParser parser;

    @NotNull
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, @NotNull WebFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();

        // 检查排除路径
        if (isExcludedPath(path)) {
            return chain.filter(exchange);
        }

        // 获取Authorization头
        String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");

        if (authHeader == null ) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }


        try {
            // 验证JWT

            Claims claims = parser
                    .parseClaimsJws(authHeader)
                    .getBody();

            // 将用户信息添加到请求属性中
            exchange.getAttributes().put("claims",claims);

            return chain.filter(exchange);
        } catch (JwtException | IllegalArgumentException ex) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
    private boolean isExcludedPath(String path) {
        return excludedPath.stream()
                .anyMatch(pathPattern -> pathPattern.equals(path));
    }


}